package com.zzty.taskapp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import com.zzty.taskapp.dao.QuestionDAO;
import com.zzty.taskapp.dao.UserDAO;
import com.zzty.taskapp.daoImpl.QuestionDAOImpl;
import com.zzty.taskapp.daoImpl.UserDAOImpl;
import com.zzty.taskapp.entity.ClassGroup;
import com.zzty.taskapp.entity.Question;
import com.zzty.taskapp.entity.SelfExam;
import com.zzty.taskapp.entity.SelfExamTransation;
import com.zzty.taskapp.entity.TeamExam;
import com.zzty.taskapp.entity.Teamexamtransation;
import com.zzty.taskapp.entity.User;
import com.zzty.taskapp.service.ClassGroupService;
import com.zzty.taskapp.service.QuestionService;
import com.zzty.taskapp.service.SelfExamService;
import com.zzty.taskapp.service.SelfExamTransationService;
import com.zzty.taskapp.service.TeamExamService;
import com.zzty.taskapp.service.TeamExamTransationService;
import com.zzty.taskapp.service.UserService;
import com.zzty.taskapp.serviceImpl.ClassGroupServiceImpl;
import com.zzty.taskapp.serviceImpl.QuestionServiceImpl;
import com.zzty.taskapp.serviceImpl.SelfExamServiceImpl;
import com.zzty.taskapp.serviceImpl.SelfExamTransationServiceImpl;
import com.zzty.taskapp.serviceImpl.TeamExamServiceImpl;
import com.zzty.taskapp.serviceImpl.TeamExamTransationServiceImpl;
import com.zzty.taskapp.serviceImpl.UserServiceImpl;

@WebServlet(name = "TeacherServlet", urlPatterns = "/TeacherServlet")
public class TeacherServlet extends HttpServlet {
	protected UserDAO ud = new UserDAOImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// super.doGet(req, resp);
		System.out.println("get====");
		QuestionDAO dao = new QuestionDAOImpl();
		List<Question> questions = new ArrayList<Question>();
		try {
			questions = dao.getAllQuestion();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(questions);
		PrintWriter out = resp.getWriter();
		out.println(json);
		out.flush();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
		PrintWriter out = resp.getWriter();
		String[] newQuestions = req.getParameterValues("newquestions");
		System.out.println("new questions "+newQuestions);
		String existingQuestionIDs = req.getParameter("formQids");

		String taskDate = req.getParameter("tdate1");

		String type = req.getParameter("taskType");

		User user = (User) req.getSession().getAttribute("user");

		QuestionService questionService = new QuestionServiceImpl();
		String questionIds = null;
		if (newQuestions != null) {
			int[] newQuestionids;
			try {
				newQuestionids = questionService.addQuestions(newQuestions);
				questionIds = formatQuestionIds(newQuestionids, existingQuestionIDs);
			} catch (Exception e) {
				e.printStackTrace();
				
				resp.sendError(500,"add question failed");
				return;
			}
			
		} else {
			questionIds = existingQuestionIDs == null ? "" : existingQuestionIDs.substring(1,existingQuestionIDs.length());
		}
		
		

		if ("team".equals(type)) {
			TeamExam te = new TeamExam();
			te.setClasses(user.getClasses());
			te.setDate(taskDate);
			te.setQuestion(questionIds);
			TeamExamService tes = new TeamExamServiceImpl();
			int teamExamId = tes.addTeamExam(te);
			ClassGroupService cgs = new ClassGroupServiceImpl();
			List<ClassGroup> groups = cgs.getGroupByClass(Integer.valueOf(user.getClasses()));
			TeamExamTransationService tets = new TeamExamTransationServiceImpl();
			if (groups != null) {
				for (int i = 0; i < groups.size(); i++) {
					Teamexamtransation tet = new Teamexamtransation();
					tet.setExameid(teamExamId);
					tet.setUserids(groups.get(i).getStuIds());
					tets.addTeamExamTransation(tet);

				}
			}

		} else {
			SelfExam se = new SelfExam();
			se.setDate(taskDate);
			se.setClazz(Integer.valueOf(user.getClasses()));
			se.setQuestions(questionIds);
			SelfExamService ses = new SelfExamServiceImpl();
			int examId = ses.saveSelfExam(se);
			UserService us = new UserServiceImpl();
			List<Integer> stuIds = us.getUsersByClazzId(user.getClasses());
			SelfExamTransationService sets = new SelfExamTransationServiceImpl();
			if (stuIds != null) {
				for (int i = 0; i < stuIds.size(); i++) {
					User newuser;
					try {
						newuser = ud.findAllByID(stuIds.get(i));
						if (newuser.getType() != 1) {
							SelfExamTransation selfTran = new SelfExamTransation();
							selfTran.setExamId(examId);
							selfTran.setUserId(stuIds.get(i));
							sets.addSelfExamTransation(selfTran);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		}

		resp.sendRedirect(req.getContextPath() + "/jsp/DataBaseSelect.jsp");

	}

	public String formatQuestionIds(int[] ids, String existingIds) {
		String result = Arrays.toString(ids).replace("[", "").replace("]", "").replaceAll(",", "|").replaceAll(" ", "");
		if (!StringUtils.isEmpty(existingIds)) {
			result = result + existingIds;
		}
		return result;
	}

}
